<script setup>
import { ref } from "vue";
import { userPWUpdateService } from "@/api/user.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { useTokenStore } from "@/stores/token.js";
import { useRouter } from "vue-router";

const router = useRouter();
const tokenStore = useTokenStore();

//定义数据模型
const pwData = ref({
  old_pwd: "",
  new_pwd: "",
  re_pwd: "",
});

const checkRePassword = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次确认密码"));
  } else if (value !== pwData.value.new_pwd) {
    callback(new Error("两次输入的密码不一致!"));
  } else {
    callback();
  }
};

//定义表单校验规则
const rules = {
  old_pwd: [
    { required: true, message: "请输入旧密码", trigger: "blur" },
    { min: 5, max: 16, message: "长度为5~16位非空字符", trigger: "blur" },
  ],
  new_pwd: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 5, max: 16, message: "长度为5~16位非空字符", trigger: "blur" },
  ],
  re_pwd: [{ required: true, validator: checkRePassword, trigger: "blur" }],
};

//修改个人信息
const updatePW = async () => {
  let result = await userPWUpdateService(pwData.value);
  ElMessage.success(result.message ? result.message : "修改成功");

  ElMessageBox.alert('请重新登录', '温馨提示', {
  confirmButtonText: '确定',
  callback: action => {
    if (action === 'confirm') {
        //退出登录
    //1.清空pinia中存储的token以及个人信息
    tokenStore.removeToken();
    //2.跳转到登录页面
    router.push("/login");
    }
  }
});

    
};
</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>重置密码</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form :rules="rules" :model="pwData" label-width="100px" size="large">
          <el-form-item prop="pwData.old_pwd" label="旧密码">
            <el-input
              type="password"
              placeholder="请输入旧密码"
              v-model="pwData.old_pwd"
            ></el-input>
          </el-form-item>
          <el-form-item prop="new_pwd" label="新密码">
            <el-input
              type="password"
              placeholder="请输入新密码"
              v-model="pwData.new_pwd"
            ></el-input>
          </el-form-item>
          <el-form-item prop="re_pwd" label="确认新密码">
            <el-input
              type="password"
              placeholder="请再次输入新密码"
              v-model="pwData.re_pwd"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePW">提交修改</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>
